import React from 'react';
import { Col, Popover, Row, Table } from 'antd';
import wechatIcon from 'images/expense/icon-wechat.png';
import alipayIcon from 'images/expense/icon-alipay.png';
import handIcon from 'images/expense/icon-hand.png';
import scanIcon from 'images/expense/icon-scan.png';
import ocrIcon from 'images/expense/icon-ocr.png';
import mailIcon from 'images/expense/icon-mail.png';
import didi from 'images/expense/icon-didi.png';
import cmbc from 'images/expense-detail/cmbc.png';
import cmbcEn from 'images/expense-detail/cmbc-en.png';
import alipay from 'images/expense-detail/alipay.png';
import alipayEn from 'images/expense-detail/alipay-en.png';
import huabei from 'images/expense-detail/huabei.png';
import huabeiEn from 'images/expense-detail/huabei-en.png';
import ReceiptChangeIcon from '../svg-component/receipt-change';
import Condition from 'components/condition';
import { messages, queryCurrencyPrecision } from 'share/common';
import INVOICE_MAP from '../service/invoice-service';

const { If, Else } = Condition;

function InvoiceOrigin(props) {
  const { origin, language } = props;
  const bussiness = {
    CMBC: {
      'en': cmbcEn,
      'zh_cn': cmbc
    },
    ALIPAY: {
      'en': alipayEn,
      'zh_cn': alipay
    },
    HUABEI: {
      'en': huabeiEn,
      'zh_cn': huabei
    }
  };
  const originMap = {
    'APPCARDSIGN': wechatIcon,
    'JSCARDSIGN': wechatIcon,
    'WXFWCARDSIGN': wechatIcon,
    'ALICARDSIGN': alipayIcon,
    'HAND': handIcon,
    'SCANNING': scanIcon,
    'OCR': ocrIcon,
    'MAIL': mailIcon,
    'DIDI': didi,
    'CMBC': bussiness.CMBC[language.code] || bussiness.CMBC['en'],
    'ALIPAY': bussiness.ALIPAY[language.code] || bussiness.ALIPAY['en'],
    'HUABEI': bussiness.HUABEI[language.code] || bussiness.HUABEI['en']
  };
  return (
    <div className="adjunct-item-origin">{messages('common.from')/*来源*/} <img src={originMap[origin] || handIcon} className="adjunct-item-icon"/></div>
  );
}


function InvoiceCell(props) {
  const { bodyWords = [], rowSpan = 12, colSpan = 8, receiptChanges = {}, currentAdjunct = {} } = props;
  return <Row type={'flex'}>
    {
      bodyWords.map(item => {
          if (item.isHide && item.isHide(currentAdjunct[item.dataIndex], currentAdjunct) || !item.name)
            return null;
          return (
            <Col span={rowSpan} className="adjunct-item-cell">
              <Row>
                <Col span={colSpan} className="adjunct-item-cell-label">
                  {item.name}：
                </Col>
                <Col span={24 - colSpan}>
                  <div
                    className={`adjunct-item-cell-content ${item.truthy && item.truthy(currentAdjunct[item.dataIndex], currentAdjunct) && 'adjunct-item-cell-error'}`}>
                    {item.render(currentAdjunct[item.dataIndex], currentAdjunct, receiptChanges[item.dataIndex])}
                  </div>
                  <If
                    value={item.truthy && item.truthy(currentAdjunct[item.dataIndex], currentAdjunct)}>
                    <div
                      className="adjunct-item-cell-truthy">{item.truthy && item.truthy(currentAdjunct[item.dataIndex], currentAdjunct)}</div>
                  </If>
                </Col>
              </Row>
            </Col>
          );
        }
      )}
  </Row>;
}



function InvoiceLabels(props) {
  const { labels = [], receiptChanges = {}, pdfDamaged, receiptLabelsDesc =[] } = props;
  let jsx_map = labels
    .map(item => (
      <div className="adjunct-item-tag-mar">
          <span className="adjunct-item-tag">
            <If value={item.type === 'MODIFY_RECEIPT'}><span className="adjunct-item-change"/></If>
            {item.name}
          </span>
      </div>)
    );
  pdfDamaged && jsx_map.push(<span className="adjunct-item-tag">{messages('expense-1.key212')/*电子票来源中的原件已损坏*/}</span>);
  receiptLabelsDesc[0] && jsx_map.push(<InvoiceLabelsDesc receiptLabelsDesc={receiptLabelsDesc} receiptChanges={receiptChanges}/>);
  return (<div className="adjunct-item-tags">{jsx_map}</div>);
}


function InvoiceLabelsDesc(props){
  const { receiptChanges, receiptLabelsDesc } = props;
  const columns = [
    {
      title: messages('expense-1.key669')/*标签名称*/,
      dataIndex: 'name',
      render: value => value
    },
    {
      title: messages('expense-1.key102')/*标签说明*/,
      dataIndex: 'description',
      render: (value, record) => (
        <Condition>
          <If value={record.type === 'MODIFY_RECEIPT'}> {messages('expense-1.key670',{arg1: Object.keys(receiptChanges).length})/*共{arg1}处改动，详细见 “_ _ _”*/}</If>
          <Else>
            <div>
              <div>{record.toast}</div>
              <div>{(record.moreDesc || '').split('\n')
                .map(item => <div>{item}</div>)}</div>
            </div>
          </Else>
        </Condition>
      )
    }
  ];
  return <Popover content={<Table pagination={false} size={'small'} rowKey={'type'} columns={columns} dataSource={receiptLabelsDesc}/>}> <span className="adjunct-item-tag adjunct-item-icon"><ReceiptChangeIcon/></span></Popover>

}

function InvoiceHeader(props) {
  const { currentReceipt: { fee, feeWithoutTax, receiptLabels, type, pdfDamaged, taxString, nonDeductibleAmount, vatInvoiceCurrencyCode }, currentReceipt, receiptChanges = {}, receiptLabelsDesc } = props;
  return (
    <section className="expense-invoice-header">
      <div className="expense-invoice-header-content">
        <div className="expense-invoice-header-title">
          {INVOICE_MAP.type.render(type, currentReceipt, receiptChanges.invoiceTypeNo)}
        </div>
        <div className="expense-invoice-header-total-amount">
          {INVOICE_MAP.vatInvoiceCurrencyCode.render(vatInvoiceCurrencyCode, currentReceipt, receiptChanges.vatInvoiceCurrencyCode)}{INVOICE_MAP.amount.render('', currentReceipt)}
        </div>
        <div className="expense-invoice-header-amount">
          {
            Object.keys({ fee, feeWithoutTax, taxString, nonDeductibleAmount })
              .map(item =>
                INVOICE_MAP[item].isHide && INVOICE_MAP[item].isHide(currentReceipt[item])
                  ? null
                  : <span>{item === 'feeWithoutTax' ? '（' : ''} {INVOICE_MAP[item].name}:  {INVOICE_MAP[item].render(currentReceipt[item], currentReceipt, receiptChanges[item])} {item === 'feeWithoutTax' ? '，' : ''} {item === 'taxString' ? ')' : ''}</span>
            )
          }
        </div>
        <If value={receiptLabels && receiptLabels.filter(item => item.type !== 'HAND_RECODE_RECEIPT')[0]}>
          <div className="expense-invoice-header-amount">
            <InvoiceLabels
              labels={receiptLabels.filter(item => item.type !== 'HAND_RECODE_RECEIPT')}
              pdfDamaged={pdfDamaged}
              receiptChanges={receiptChanges}
              receiptLabelsDesc={receiptLabelsDesc}
            />
          </div>
        </If>
      </div>
    </section>
  );
}

function InvoiceGoods(props) {
  const { currentReceipt: { invoiceGoods, invoiceTypeNo, blockchain } } = props;
  const columns = [
      {
        title: messages('expense-1.key67')/*货物或应税劳务、服务名称*/,
        dataIndex: 'goodsName',
        width: '30%',
        render: goodsName => <div style={{
          wordWrap: 'break-word',
          wordBreak: 'break-word',
          whiteSpace: 'normal',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }}>
          {goodsName || '-'}
        </div>
      },
      {
        title: messages('expense-1.key68')/*规格型号*/,
        dataIndex: 'vehicleType',
        render: vehicleType => vehicleType || '-'
      },
      {
        title: messages('common.unit')/*单位*/, dataIndex: 'unit'
      },
      {
        title: messages('common.number')/*数量*/, dataIndex: 'count'
      },
      {
        title: messages('common.price')/*单价*/,
        dataIndex: 'unitPrice',
        render: (unitPrice, item) => (Number(unitPrice) / 100).toFixed(queryCurrencyPrecision(item.vatInvoiceCurrencyCode))
      },
      {
        title: messages('common.amount')/*金额*/,
        dataIndex: 'amount',
        render: (amount, item) => (amount !== undefined && amount !== null) ? (Number(amount) / 100).toFixed(queryCurrencyPrecision(item.vatInvoiceCurrencyCode)) : '-'
      },
      {
        title: messages('expense-1.key69')/*税率*/,
        dataIndex: 'taxRateString',
        render: value => (value !== undefined && value !== null) ? (isNaN(value) ? value : `${value}%`) : '-'
      },
      {
        title: messages('common.tax')/*税额*/,
        dataIndex: 'taxPrice',
        render: (taxPrice, item) => (taxPrice !== undefined && taxPrice !== null) ?
          (isNaN(taxPrice) ? taxPrice : (Number(taxPrice) / 100).toFixed(queryCurrencyPrecision(item.vatInvoiceCurrencyCode))) : '-'
      }
    ],
    travelColumns = [
      {
        title: messages('expense-1.key70')/*项目名称*/,
        dataIndex: 'goodsName',
        width: '23%',
        render: goodsName => goodsName || '-'
      },
      {
        title: messages('expense-1.key71')/*车牌号*/,
        dataIndex: 'plateNumber',
        width: '13%',
        render: plateNumber => plateNumber || '-'
      },
      {
        title: messages('expense-1.key72')/*类型*/,
        dataIndex: 'carType',
        width: '8%',
        render: carType => carType || '-'
      },
      {
        title: messages('expense-1.key73')/*通行日期起*/,
        dataIndex: 'passDateFrom',
        width: '17%',
        render: passDateFrom => passDateFrom || '-'
      },
      {
        title: messages('expense-1.key74')/*通行日期至*/,
        dataIndex: 'passDateTo',
        width: '17%',
        render: passDateTo => passDateTo || '-'
      },
      {
        title: messages('common.amount')/*金额*/,
        dataIndex: 'amount',
        width: '8%',
        render: (amount, item) => (amount !== undefined && amount !== null) ? (Number(amount) / 100).toFixed(queryCurrencyPrecision(item.vatInvoiceCurrencyCode)) : '-'
      },
      {
        title: messages('expense-1.key69')/*税率*/,
        dataIndex: 'taxRateString',
        width: '8%',
        render: value => (value !== undefined && value !== null) ? (isNaN(value) ? value : `${value}%`) : '-'
      },
      {
        title: messages('common.tax')/*税额*/,
        dataIndex: 'taxPrice',
        width: '8%',
        render: (taxPrice, item) => (taxPrice !== undefined && taxPrice !== null) ?
          (isNaN(taxPrice) ? taxPrice : (Number(taxPrice) / 100).toFixed(queryCurrencyPrecision(item.vatInvoiceCurrencyCode))) : '-'
      }
    ];

  return (
    <section className="expense-invoice-goods">
      <div className="expense-invoice-goods-title">{messages('expense-1.key671')/*商品信息*/}</div>
      <Table
        size="small"
        style={{ margin: '12px 0' }}
        columns={invoiceTypeNo !== '14' ? columns : travelColumns}
        dataSource={invoiceGoods}
        rowKey={(record, index) => index}
        pagination={false}
        locale={{ emptyText: blockchain ? messages('expense-1.key672')/*区块链发票：国税局不支持查验，无法获取发票行信息*/ : messages('common.empty.text')/*暂无数据*/ }}
      />
    </section>
  );
}

function Annex(props) {
  const { currentAdjunct: { fileName } } = props;
  return (
    <section  className={`${props.className} adjunct-detail-annex`}>
      {fileName}
    </section>
  );
}

export {
  InvoiceOrigin,
  InvoiceCell,
  InvoiceLabels,
  InvoiceHeader,
  InvoiceGoods,
  Annex
};
